import style from './render/style'
import Layout from './engine'

let __env = GameGlobal.wx || GameGlobal.tt || GameGlobal.swan;
let sharedCanvas = __env.getSharedCanvas();
let sharedContext = sharedCanvas.getContext('2d');



function updateViewPort(data) {
    Layout.updateViewPort({
        x: data.x,
        y: data.y,
        width: data.width,
        height: data.height,
    });
}

function showFriendList() {
    return new Promise(function(resolve, reject) {
        let dataDemo = {
            data: [],
        };
        wx.getFriendCloudStorage({
            keyList: ['rank_all'],
            success: function(res) {
                dataDemo.data = []
                if (res.data != null && res.data.length > 0) {
                    for (let i = 0; i < res.data.length; i++) {

                        let item = {};
                        const dataStr = res.data[i].KVDataList[0].value
                        const data = JSON.parse(dataStr)
                        item.avatarUrl = data.avatarUrl
                        item.nickName = data.nickName
                        item.maxLevel = data.maxLevel
                        dataDemo.data.push(item);

                    }
                }
                dataDemo.data.sort((a, b)=>a.maxLevel - b.maxLevel)
                resolve(dataDemo)
            },
            fail: function(res) {
                resolve(dataDemo)
            },
            complete: function(res) {
            },
        })
    })
}

function getTemplate(it, type) {
    var out = '<view class="container"> <scrollview class="array"> ';
    var arr1 = it.data;
    if (arr1) {
        var item, index = -1,
            l1 = arr1.length - 1;
        while (index < l1) {
            item = arr1[index += 1];
            out += ' ';
            if (index % 2 === 1) { out += ' <view class="listItem"> '; }
            out += ' ';
            if (index % 2 === 0) { out += ' <view class="listItem listItemOld"> '; }
            out += ' <view id="listItemUserData"> <text class="listItemNum" value="' + (index + 1) + '"></text> <image class="listHeadImg" src="' + (item.avatarUrl) + '"></image> <text class="listItemName" value="' + (item.nickName)
                +
                '"></text> </view>'
            out += ' <text class="listItemButton" value="'+item.maxLevel+'关"></text></view> ';
            

        }
    }
    out += ' </scrollview></view>';
    return out
}

__env.onMessage(data => {
    console.info('data:', data)
    if (data.event === 'viewport') {
        updateViewPort(data)
    }

    if (data.type === 'rank_all') {
        showFriendList().then(res => {
            let dataDemo = res
            let template = getTemplate(dataDemo, data.type)

            Layout.clear();
            Layout.init(template, style);
            Layout.layout(sharedContext);
        })
    }
});